In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Make sure that you've downloaded the required human and dog datasets:
Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.
Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.
Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.
import numpy as np
from glob import glob
# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))
# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images. There are 8351 total dog images.
In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.
OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer: (You can print out your results and/or write your percentages in this cell)
from tqdm import tqdm
human_files_short = human_files[:100]
dog_files_short = dog_files[:100]
#-#-# Do NOT modify the code above this line. #-#-#
## Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
falsePositiveList = []
trueNegativeList = []
with tqdm(total=100) as progresBar:
progresBar.set_description('Human faces found in human face images')
length = len(human_files_short)
for image in human_files_short:
if (face_detector(image)):
progresBar.update(1. / length * 100)
else:
trueNegativeList.append(image)
with tqdm(total=100) as progresBar:
progresBar.set_description('Human faces found in dog images')
length = len(dog_files_short)
for image in dog_files_short:
if (face_detector(image)):
falsePositiveList.append(image)
progresBar.update(1. / length * 100)
Human faces found in human face images: 98%|█████████▊| 98.0/100 [00:01<00:00, 61.14it/s] Human faces found in dog images: 9%|▉ | 9.0/100 [00:06<01:00, 1.50it/s]
fig = plt.figure(figsize=(4, 4))
fig.suptitle('Undetectable Human Faces', fontsize=12)
for i, imageFile in enumerate(trueNegativeList):
ax = fig.add_subplot(1, len(trueNegativeList), i+1, xticks=[], yticks=[])
image = cv2.imread(imageFile)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
ax.imshow(image)
fig = plt.figure(figsize=(32, 32))
for i, imageFile in enumerate(falsePositiveList):
ax = fig.add_subplot(1, len(falsePositiveList), i+1, xticks=[], yticks=[])
image = cv2.imread(imageFile)
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(grayImage)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
ax.imshow(image)
Some dog faces were detected as human face. One image contains human and dog together. In other images, there are places like human face classified by detector.
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.
# I use dlib's HoG-SVM based face detector.
# To execute cells, dlib must be installed in your Python environment
# It is built out of 5 HOG filters. A front looking, left looking, right looking,
# front looking but rotated left, and finally a front looking but rotated right one.
import dlib
def hogFaceDetector(imagePath):
image = cv2.imread(imagePath)
detector = dlib.get_frontal_face_detector()
faceRects = detector(image)
return len(faceRects) > 0
falsePositiveListHoG = []
trueNegativeListHoG = []
with tqdm(total=100) as progresBar:
progresBar.set_description('Human faces found in human face images with HoG-SVM')
length = len(human_files_short)
for image in human_files_short:
if (hogFaceDetector(image)):
progresBar.update(1. / length * 100)
else:
trueNegativeListHoG.append(image)
with tqdm(total=100) as progresBar:
progresBar.set_description('Human faces found in dog images with HoG-SVM')
length = len(dog_files_short)
for image in dog_files_short:
if (hogFaceDetector(image)):
falsePositiveListHoG.append(image)
progresBar.update(1. / length * 100)
Human faces found in human face images with HoG-SVM: 100%|██████████| 100.0/100 [00:36<00:00, 2.73it/s] Human faces found in dog images with HoG-SVM: 7%|▋ | 7.0/100 [00:40<08:59, 5.80s/it]
fig = plt.figure(figsize=(32, 32))
detectorHoG = dlib.get_frontal_face_detector()
for i, imageFile in enumerate(falsePositiveListHoG):
ax = fig.add_subplot(1, len(falsePositiveListHoG), i+1, xticks=[], yticks=[])
image = cv2.imread(imageFile)
faceRects = detectorHoG(image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
for rect in faceRects:
cv2.rectangle(image, (rect.left(), rect.top()), (rect.right(), rect.bottom()),(255,0,0),2)
ax.imshow(image)
It seems HoG-SVM based face detector is working more accurate than cascade classifier.
In this section, we use a pre-trained model to detect dogs in images.
The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.
import torch
import torchvision.models as models
# check if CUDA is available
use_cuda = torch.cuda.is_available()
use_cuda
True
# define VGG16 model
VGG16 = models.vgg16(pretrained=True).eval()
# move model to GPU if CUDA is available
if use_cuda:
VGG16 = VGG16.cuda()
Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.
In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.
Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.
from PIL import Image
import torchvision.transforms as transforms
# Set PIL to be tolerant of image files that are truncated.
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# https://github.com/pytorch/examples/blob/42e5b996718797e45c46a25c55b031e6768f8440/imagenet/main.py#L89-L101
transformsListVGG16 = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
def VGG16_predict(imagePath):
'''
Use pre-trained VGG-16 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to VGG-16 model's prediction
'''
## Load and pre-process an image from the given img_path
## Return the *index* of the predicted class for that image
image = Image.open(imagePath)
inputTensor = transformsListVGG16(image).unsqueeze(0)
if (use_cuda):
inputTensor = inputTensor.cuda()
outputTensor = VGG16(inputTensor)
_, prediction = torch.max(outputTensor, 1)
return prediction.cpu().item() # predicted class index
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).
Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
## TODO: Complete the function.
index = VGG16_predict(img_path)
return ((index > 150) and (index < 269)) # true/false
dog_detector('dogImages/train/001.Affenpinscher/Affenpinscher_00013.jpg')
True
Question 2: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
### Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
falsePositiveListVGG16 = []
with tqdm(total=100) as progresBar:
progresBar.set_description('Dogs found in human face images with VGG16')
length = len(human_files_short)
numOfDogsFound = 0
for image in human_files_short:
if (dog_detector(image)):
falsePositiveListVGG16.append(image)
numOfDogsFound += 1
#progresBar.update(1. / length * 100)
progresBar.update(numOfDogsFound / length * 100)
Dogs found in human face images with VGG16: 1%| | 1.0/100 [00:01<02:22, 1.44s/it]
falsePositiveListVGG16
['lfw/Queen_Elizabeth_II/Queen_Elizabeth_II_0013.jpg']
trueNegativeListVGG16 = []
with tqdm(total=100) as progresBar:
progresBar.set_description('Dogs found in dog images with VGG16')
length = len(dog_files_short)
numOfDogsFound = 0
for image in dog_files_short:
if (dog_detector(image)):
#progresBar.update(1. / length * 100)
numOfDogsFound += 1
else:
trueNegativeListVGG16.append(image)
progresBar.update(numOfDogsFound / length * 100)
Dogs found in dog images with VGG16: 100%|██████████| 100.0/100 [00:02<00:00, 46.01it/s]
trueNegativeListVGG16
[]
We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
import os
from torchvision import datasets
### Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
workspaceDir = os.getcwd()
datasetDir = 'dogImages'
batchSize = 32
numberOfWorkers = 8
trainingTransformsList = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.RandomResizedCrop(size=(224, 224), scale=(0.8, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=(-10, 10)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
validationTransformsList = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
testTransformsList = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
transformsList = {'train' : trainingTransformsList, 'valid' : validationTransformsList, 'test' : testTransformsList}
datasets = {key : datasets.ImageFolder(os.path.join(workspaceDir, datasetDir, key), transformsList[key]) for key in transformsList}
loaders_scratch = {key : torch.utils.data.DataLoader(
datasets[key],
batch_size=batchSize,
shuffle=True,
num_workers=numberOfWorkers) for key in transformsList
}
import matplotlib.pyplot as plt
%matplotlib inline
# obtain one batch of training images
dataiter = iter(loaders_scratch['train'])
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
# display 20 images
for idx in np.arange(20):
ax = fig.add_subplot(2, 20//2, idx+1, xticks=[], yticks=[])
image = images[idx].transpose((1, 2, 0))
image = image * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
image = np.clip(image, 0.0, 1.0)
plt.imshow(image)
ax.set_title(datasets['train'].classes[labels[idx]][4:])
len(datasets['train'].classes)
133
Question 3: Describe your chosen procedure for preprocessing the data.
Answer: I used 224x224 image resolution for training, validation and test. The input image is resized to 256x256 firstly then cropped randomly and resized to 224x224. I used data augmentation in the train dataset. For training, I used horizontal flip and some rotation to make training with more variation.
Create a CNN to classify dog breed. Use the template in the code cell below.
import torch.nn as nn
import torch.nn.functional as F
# define the CNN architecture
class Net(nn.Module):
### choose an architecture, and complete the class
def __init__(self, numberOfClasses: int = 133):
super(Net, self).__init__()
## Define layers of a CNN
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=2), #divides by 2
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), #divides by 2
#->32x56x56
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout2d(0.0625),
#->64x28x28
nn.Conv2d(64, 96, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(96),
nn.ReLU(),
nn.Conv2d(96, 128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout2d(0.125),
#->128x14x14
nn.Conv2d(128, 64, kernel_size=1, stride=1, padding=0),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout2d(0.25),
#->256x7x7
nn.Conv2d(256, 64, kernel_size=1, stride=1, padding=0),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
# Just pool, do not resize
nn.MaxPool2d(kernel_size=2, stride=1),
#512x6x6
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(512 * 6 * 6, 2048),
nn.ReLU(),
nn.Dropout(),
nn.Linear(2048, 1024),
nn.ReLU(),
nn.Dropout(),
nn.Linear(1024, numberOfClasses),
)
def forward(self, x):
## Define forward behavior
x = self.features(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
#-#-# You do NOT have to modify the code below this line. #-#-#
# instantiate the CNN
model_scratch = Net(numberOfClasses=len(datasets['train'].classes))
# move tensors to GPU if CUDA is available
if use_cuda:
torch.cuda.empty_cache()
model_scratch.cuda()
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer: The architecture must contain convolutional and MLP layers. Convolutional layers extracts features and named as features in the network I created. MLP layers make classification and are named as classifier in the network. The input size of the network is 3x224x244 and the output is 1x133 to classify dog breeds. Convolutional layers start with 5x5 convolution with stride 2 and max pooling with stride 2. I didn't want to make too much computation with high resolution patches and used stride 2 in 5x5 kernel and max pooling layer. The last layer of the features layer produces 512x6x6 patches and it is small enough to pass MLP layer with flattening. I used 1x1 convolutions in the network, to make network deeper without much multiplication and addition. 1x1 convolutions is used to re-sample its input layer and makes output smaller. After every 1x1 convolutions, I made network deeper with factor 2. After convolutions, I added max pooling layers, to make patches smaller. While pathes are getting smaller, layers becomes deeper. I added dropout layers to prevent overfitting.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.
import torch.optim as optim
### select loss function
criterion_scratch = nn.CrossEntropyLoss()
### select optimizer
learning_rate = 1e-4
optimizer_scratch = torch.optim.Adam(model_scratch.parameters(), lr=learning_rate)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.
# the following import is required for training to be robust to truncated images
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
"""returns trained model"""
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs+1):
# initialize variables to monitor training and validation loss
train_loss = 0.0
valid_loss = 0.0
###################
# train the model #
###################
model.train()
for batch_idx, (data, target) in enumerate(loaders['train']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## find the loss and update the model parameters accordingly
## record the average training loss, using something like
## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
# clear the gradients of all optimized variables
optimizer.zero_grad()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# backward pass: compute gradient of the loss with respect to model parameters
loss.backward()
# perform a single optimization step (parameter update)
optimizer.step()
# update training loss
train_loss += loss.item()*data.size(0)
######################
# validate the model #
######################
model.eval()
for batch_idx, (data, target) in enumerate(loaders['valid']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## update the average validation loss
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# update average validation loss
valid_loss += loss.item()*data.size(0)
# calculate average losses
train_loss = train_loss / len(loaders['train'].dataset)
valid_loss = valid_loss / len(loaders['valid'].dataset)
# print training/validation statistics
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch,
train_loss,
valid_loss
))
## save the model if validation loss has decreased
if valid_loss <= valid_loss_min:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(
valid_loss_min,
valid_loss))
torch.save(model.state_dict(), save_path)
valid_loss_min = valid_loss
# return trained model
return model
# train the model
modelFilePath = os.path.join(os.getcwd(), 'model_scratch.pt')
model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch,
criterion_scratch, use_cuda, modelFilePath)
Epoch: 1 Training Loss: 4.946196 Validation Loss: 4.842882 Validation loss decreased (inf --> 4.842882). Saving model ... Epoch: 2 Training Loss: 4.821763 Validation Loss: 4.736626 Validation loss decreased (4.842882 --> 4.736626). Saving model ... Epoch: 3 Training Loss: 4.755983 Validation Loss: 4.650857 Validation loss decreased (4.736626 --> 4.650857). Saving model ... Epoch: 4 Training Loss: 4.653585 Validation Loss: 4.537089 Validation loss decreased (4.650857 --> 4.537089). Saving model ... Epoch: 5 Training Loss: 4.537534 Validation Loss: 4.382857 Validation loss decreased (4.537089 --> 4.382857). Saving model ... Epoch: 6 Training Loss: 4.416754 Validation Loss: 4.253164 Validation loss decreased (4.382857 --> 4.253164). Saving model ... Epoch: 7 Training Loss: 4.319194 Validation Loss: 4.224824 Validation loss decreased (4.253164 --> 4.224824). Saving model ... Epoch: 8 Training Loss: 4.254749 Validation Loss: 4.114844 Validation loss decreased (4.224824 --> 4.114844). Saving model ... Epoch: 9 Training Loss: 4.177423 Validation Loss: 4.077862 Validation loss decreased (4.114844 --> 4.077862). Saving model ... Epoch: 10 Training Loss: 4.114508 Validation Loss: 3.987074 Validation loss decreased (4.077862 --> 3.987074). Saving model ... Epoch: 11 Training Loss: 4.066305 Validation Loss: 3.929865 Validation loss decreased (3.987074 --> 3.929865). Saving model ... Epoch: 12 Training Loss: 4.019740 Validation Loss: 3.924896 Validation loss decreased (3.929865 --> 3.924896). Saving model ... Epoch: 13 Training Loss: 3.958634 Validation Loss: 3.830813 Validation loss decreased (3.924896 --> 3.830813). Saving model ... Epoch: 14 Training Loss: 3.898064 Validation Loss: 3.777615 Validation loss decreased (3.830813 --> 3.777615). Saving model ... Epoch: 15 Training Loss: 3.847356 Validation Loss: 3.749757 Validation loss decreased (3.777615 --> 3.749757). Saving model ... Epoch: 16 Training Loss: 3.796024 Validation Loss: 3.682963 Validation loss decreased (3.749757 --> 3.682963). Saving model ... Epoch: 17 Training Loss: 3.762142 Validation Loss: 3.698936 Epoch: 18 Training Loss: 3.719751 Validation Loss: 3.643397 Validation loss decreased (3.682963 --> 3.643397). Saving model ... Epoch: 19 Training Loss: 3.661030 Validation Loss: 3.573479 Validation loss decreased (3.643397 --> 3.573479). Saving model ... Epoch: 20 Training Loss: 3.634705 Validation Loss: 3.485455 Validation loss decreased (3.573479 --> 3.485455). Saving model ... Epoch: 21 Training Loss: 3.585604 Validation Loss: 3.470550 Validation loss decreased (3.485455 --> 3.470550). Saving model ... Epoch: 22 Training Loss: 3.540379 Validation Loss: 3.454309 Validation loss decreased (3.470550 --> 3.454309). Saving model ... Epoch: 23 Training Loss: 3.484002 Validation Loss: 3.427964 Validation loss decreased (3.454309 --> 3.427964). Saving model ... Epoch: 24 Training Loss: 3.446652 Validation Loss: 3.353156 Validation loss decreased (3.427964 --> 3.353156). Saving model ... Epoch: 25 Training Loss: 3.411653 Validation Loss: 3.313267 Validation loss decreased (3.353156 --> 3.313267). Saving model ... Epoch: 26 Training Loss: 3.367856 Validation Loss: 3.322221 Epoch: 27 Training Loss: 3.326780 Validation Loss: 3.288268 Validation loss decreased (3.313267 --> 3.288268). Saving model ... Epoch: 28 Training Loss: 3.288896 Validation Loss: 3.239861 Validation loss decreased (3.288268 --> 3.239861). Saving model ... Epoch: 29 Training Loss: 3.242100 Validation Loss: 3.252047 Epoch: 30 Training Loss: 3.203287 Validation Loss: 3.215980 Validation loss decreased (3.239861 --> 3.215980). Saving model ... Epoch: 31 Training Loss: 3.150738 Validation Loss: 3.234398 Epoch: 32 Training Loss: 3.107898 Validation Loss: 3.127635 Validation loss decreased (3.215980 --> 3.127635). Saving model ... Epoch: 33 Training Loss: 3.083213 Validation Loss: 3.087518 Validation loss decreased (3.127635 --> 3.087518). Saving model ... Epoch: 34 Training Loss: 3.052209 Validation Loss: 3.020723 Validation loss decreased (3.087518 --> 3.020723). Saving model ... Epoch: 35 Training Loss: 2.993196 Validation Loss: 3.081328 Epoch: 36 Training Loss: 2.954974 Validation Loss: 3.031657 Epoch: 37 Training Loss: 2.946281 Validation Loss: 3.050196 Epoch: 38 Training Loss: 2.897062 Validation Loss: 2.998501 Validation loss decreased (3.020723 --> 2.998501). Saving model ... Epoch: 39 Training Loss: 2.860803 Validation Loss: 2.977767 Validation loss decreased (2.998501 --> 2.977767). Saving model ... Epoch: 40 Training Loss: 2.818027 Validation Loss: 2.904043 Validation loss decreased (2.977767 --> 2.904043). Saving model ... Epoch: 41 Training Loss: 2.761157 Validation Loss: 2.864212 Validation loss decreased (2.904043 --> 2.864212). Saving model ... Epoch: 42 Training Loss: 2.735557 Validation Loss: 2.805785 Validation loss decreased (2.864212 --> 2.805785). Saving model ... Epoch: 43 Training Loss: 2.696032 Validation Loss: 2.866347 Epoch: 44 Training Loss: 2.653537 Validation Loss: 2.891598 Epoch: 45 Training Loss: 2.630822 Validation Loss: 2.794016 Validation loss decreased (2.805785 --> 2.794016). Saving model ... Epoch: 46 Training Loss: 2.588965 Validation Loss: 2.702798 Validation loss decreased (2.794016 --> 2.702798). Saving model ... Epoch: 47 Training Loss: 2.574104 Validation Loss: 2.760773 Epoch: 48 Training Loss: 2.515245 Validation Loss: 2.642157 Validation loss decreased (2.702798 --> 2.642157). Saving model ... Epoch: 49 Training Loss: 2.506193 Validation Loss: 2.653894 Epoch: 50 Training Loss: 2.458940 Validation Loss: 2.762238 Epoch: 51 Training Loss: 2.438804 Validation Loss: 2.702669 Epoch: 52 Training Loss: 2.377653 Validation Loss: 2.618923 Validation loss decreased (2.642157 --> 2.618923). Saving model ... Epoch: 53 Training Loss: 2.391324 Validation Loss: 2.554233 Validation loss decreased (2.618923 --> 2.554233). Saving model ... Epoch: 54 Training Loss: 2.335236 Validation Loss: 2.549368 Validation loss decreased (2.554233 --> 2.549368). Saving model ... Epoch: 55 Training Loss: 2.278665 Validation Loss: 2.486071 Validation loss decreased (2.549368 --> 2.486071). Saving model ... Epoch: 56 Training Loss: 2.244385 Validation Loss: 2.481621 Validation loss decreased (2.486071 --> 2.481621). Saving model ... Epoch: 57 Training Loss: 2.241819 Validation Loss: 2.458562 Validation loss decreased (2.481621 --> 2.458562). Saving model ... Epoch: 58 Training Loss: 2.224080 Validation Loss: 2.472567 Epoch: 59 Training Loss: 2.217925 Validation Loss: 2.487364 Epoch: 60 Training Loss: 2.166478 Validation Loss: 2.387101 Validation loss decreased (2.458562 --> 2.387101). Saving model ... Epoch: 61 Training Loss: 2.155433 Validation Loss: 2.423911 Epoch: 62 Training Loss: 2.105138 Validation Loss: 2.401044 Epoch: 63 Training Loss: 2.102809 Validation Loss: 2.408370 Epoch: 64 Training Loss: 2.078800 Validation Loss: 2.381401 Validation loss decreased (2.387101 --> 2.381401). Saving model ... Epoch: 65 Training Loss: 2.022918 Validation Loss: 2.357807 Validation loss decreased (2.381401 --> 2.357807). Saving model ... Epoch: 66 Training Loss: 2.018219 Validation Loss: 2.391765 Epoch: 67 Training Loss: 2.020040 Validation Loss: 2.362897 Epoch: 68 Training Loss: 1.993102 Validation Loss: 2.283675 Validation loss decreased (2.357807 --> 2.283675). Saving model ... Epoch: 69 Training Loss: 1.962896 Validation Loss: 2.236757 Validation loss decreased (2.283675 --> 2.236757). Saving model ... Epoch: 70 Training Loss: 1.926767 Validation Loss: 2.283553 Epoch: 71 Training Loss: 1.921266 Validation Loss: 2.318101 Epoch: 72 Training Loss: 1.877440 Validation Loss: 2.268990 Epoch: 73 Training Loss: 1.877561 Validation Loss: 2.275021 Epoch: 74 Training Loss: 1.872811 Validation Loss: 2.268456 Epoch: 75 Training Loss: 1.837702 Validation Loss: 2.273902 Epoch: 76 Training Loss: 1.829816 Validation Loss: 2.247207 Epoch: 77 Training Loss: 1.833507 Validation Loss: 2.289237 Epoch: 78 Training Loss: 1.771223 Validation Loss: 2.154845 Validation loss decreased (2.236757 --> 2.154845). Saving model ... Epoch: 79 Training Loss: 1.796629 Validation Loss: 2.176818 Epoch: 80 Training Loss: 1.779293 Validation Loss: 2.206100 Epoch: 81 Training Loss: 1.740747 Validation Loss: 2.142783 Validation loss decreased (2.154845 --> 2.142783). Saving model ... Epoch: 82 Training Loss: 1.713115 Validation Loss: 2.189311 Epoch: 83 Training Loss: 1.711410 Validation Loss: 2.110282 Validation loss decreased (2.142783 --> 2.110282). Saving model ... Epoch: 84 Training Loss: 1.681478 Validation Loss: 2.082067 Validation loss decreased (2.110282 --> 2.082067). Saving model ... Epoch: 85 Training Loss: 1.660420 Validation Loss: 2.161771 Epoch: 86 Training Loss: 1.633051 Validation Loss: 2.165567 Epoch: 87 Training Loss: 1.623069 Validation Loss: 2.125299 Epoch: 88 Training Loss: 1.594658 Validation Loss: 2.203318 Epoch: 89 Training Loss: 1.624841 Validation Loss: 2.137926 Epoch: 90 Training Loss: 1.569690 Validation Loss: 2.215009 Epoch: 91 Training Loss: 1.585330 Validation Loss: 2.080210 Validation loss decreased (2.082067 --> 2.080210). Saving model ... Epoch: 92 Training Loss: 1.572535 Validation Loss: 2.140715 Epoch: 93 Training Loss: 1.516787 Validation Loss: 2.139699 Epoch: 94 Training Loss: 1.512924 Validation Loss: 2.193249 Epoch: 95 Training Loss: 1.527549 Validation Loss: 2.096047 Epoch: 96 Training Loss: 1.491329 Validation Loss: 2.129387 Epoch: 97 Training Loss: 1.497119 Validation Loss: 2.074338 Validation loss decreased (2.080210 --> 2.074338). Saving model ... Epoch: 98 Training Loss: 1.449559 Validation Loss: 2.128354 Epoch: 99 Training Loss: 1.479860 Validation Loss: 2.048949 Validation loss decreased (2.074338 --> 2.048949). Saving model ... Epoch: 100 Training Loss: 1.457765 Validation Loss: 2.073632
import shutil
modelEvalFilePath = os.path.join(os.getcwd(), 'model_scratch_eval.pt')
shutil.copyfile(modelFilePath, modelEvalFilePath)
'/edisk/src/project-dog-classification/model_scratch_eval.pt'
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load(modelEvalFilePath))
<All keys matched successfully>
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
# compare predictions to true label
correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
total += data.size(0)
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
# call test function
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 2.062913 Test Accuracy: 46% (387/836)
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
## Specify data loaders
loaders_transfer = {key : torch.utils.data.DataLoader(
datasets[key],
batch_size=32,
shuffle=True,
num_workers=8) for key in transformsList
}
Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.
import torchvision.models as models
import torch.nn as nn
## TODO: Specify model architecture
model_transfer = models.resnet101(pretrained=True)
for param in model_transfer.parameters():
param.requires_grad = False
model_transfer
track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer2): Sequential(
(0): Bottleneck(
(conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(3): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer3): Sequential(
(0): Bottleneck(
(conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(3): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(4): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(5): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(6): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(7): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(8): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(9): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(10): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(11): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(12): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(13): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(14): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(15): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(16): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(17): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(18): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(19): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(20): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(21): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(22): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer4): Sequential(
(0): Bottleneck(
(conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
(fc): Linear(in_features=2048, out_features=1000, bias=True)
)
model_transfer.fc = nn.Linear(2048, len(datasets['train'].classes))
if use_cuda:
torch.cuda.empty_cache()
model_transfer = model_transfer.cuda()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: I used resnet101 model. It is designed to classify images in ImageNet. Since the pre-trained model has ability to classify dog breeds, we can use it by changing fully connected layer. The original FC layer has 2048 inputs and 1000 outputs for 1000 classes. I changed FC layer as 2048 inputs and 133 outputs for dog breed classification task. I freezed convolutional layers of the model for training. By doing that, only FC layer is trained by our dog breed classification images.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.
criterion_transfer = nn.CrossEntropyLoss()
learning_rate = 1e-4
optimizer_transfer = torch.optim.Adam(model_transfer.parameters(), lr=learning_rate)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# train the model
n_epochs = 25
modelTransferFilePath = os.path.join(os.getcwd(), 'model_transfer.pt')
model_transfer = train(n_epochs, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, modelTransferFilePath)
Epoch: 1 Training Loss: 4.140708 Validation Loss: 3.254353 Validation loss decreased (inf --> 3.254353). Saving model ... Epoch: 2 Training Loss: 2.792449 Validation Loss: 2.165941 Validation loss decreased (3.254353 --> 2.165941). Saving model ... Epoch: 3 Training Loss: 1.955609 Validation Loss: 1.575957 Validation loss decreased (2.165941 --> 1.575957). Saving model ... Epoch: 4 Training Loss: 1.473435 Validation Loss: 1.239221 Validation loss decreased (1.575957 --> 1.239221). Saving model ... Epoch: 5 Training Loss: 1.198582 Validation Loss: 1.019471 Validation loss decreased (1.239221 --> 1.019471). Saving model ... Epoch: 6 Training Loss: 1.012161 Validation Loss: 0.881382 Validation loss decreased (1.019471 --> 0.881382). Saving model ... Epoch: 7 Training Loss: 0.883425 Validation Loss: 0.778019 Validation loss decreased (0.881382 --> 0.778019). Saving model ... Epoch: 8 Training Loss: 0.789179 Validation Loss: 0.721423 Validation loss decreased (0.778019 --> 0.721423). Saving model ... Epoch: 9 Training Loss: 0.717449 Validation Loss: 0.678529 Validation loss decreased (0.721423 --> 0.678529). Saving model ... Epoch: 10 Training Loss: 0.662526 Validation Loss: 0.634509 Validation loss decreased (0.678529 --> 0.634509). Saving model ... Epoch: 11 Training Loss: 0.617484 Validation Loss: 0.591990 Validation loss decreased (0.634509 --> 0.591990). Saving model ... Epoch: 12 Training Loss: 0.580452 Validation Loss: 0.570485 Validation loss decreased (0.591990 --> 0.570485). Saving model ... Epoch: 13 Training Loss: 0.536506 Validation Loss: 0.536794 Validation loss decreased (0.570485 --> 0.536794). Saving model ... Epoch: 14 Training Loss: 0.512591 Validation Loss: 0.535572 Validation loss decreased (0.536794 --> 0.535572). Saving model ... Epoch: 15 Training Loss: 0.482393 Validation Loss: 0.511933 Validation loss decreased (0.535572 --> 0.511933). Saving model ... Epoch: 16 Training Loss: 0.463843 Validation Loss: 0.491290 Validation loss decreased (0.511933 --> 0.491290). Saving model ... Epoch: 17 Training Loss: 0.438377 Validation Loss: 0.469166 Validation loss decreased (0.491290 --> 0.469166). Saving model ... Epoch: 18 Training Loss: 0.430830 Validation Loss: 0.476207 Epoch: 19 Training Loss: 0.408776 Validation Loss: 0.480537 Epoch: 20 Training Loss: 0.397450 Validation Loss: 0.462890 Validation loss decreased (0.469166 --> 0.462890). Saving model ... Epoch: 21 Training Loss: 0.387295 Validation Loss: 0.438865 Validation loss decreased (0.462890 --> 0.438865). Saving model ... Epoch: 22 Training Loss: 0.371985 Validation Loss: 0.431844 Validation loss decreased (0.438865 --> 0.431844). Saving model ... Epoch: 23 Training Loss: 0.356285 Validation Loss: 0.439541 Epoch: 24 Training Loss: 0.338966 Validation Loss: 0.426335 Validation loss decreased (0.431844 --> 0.426335). Saving model ... Epoch: 25 Training Loss: 0.329767 Validation Loss: 0.422569 Validation loss decreased (0.426335 --> 0.422569). Saving model ...
modelTransferEvalFilePath = os.path.join(os.getcwd(), 'model_transfer_eval.pt')
shutil.copyfile(modelTransferFilePath, modelTransferEvalFilePath)
'/edisk/src/project-dog-classification/model_transfer_eval.pt'
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load(modelTransferEvalFilePath))
<All keys matched successfully>
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 0.434507 Test Accuracy: 88% (741/836)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.
### Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
# list of class names by index, i.e. a name can be accessed like class_names[0]
data_transfer = datasets
class_names = [item[4:].replace("_", " ") for item in data_transfer['train'].classes]
model_transfer = model_transfer.eval()
def predict_breed_transfer(img_path):
# load the image and return the predicted breed
image = Image.open(img_path)
inputTensor = transformsList['test'](image).unsqueeze(0)
if (use_cuda):
inputTensor = inputTensor.cuda()
outputTensor = model_transfer(inputTensor)
_, prediction = torch.max(outputTensor, 1)
if (use_cuda):
prediction = prediction.cpu().item()
else:
prediction = prediction.item()
return class_names[prediction]
print(predict_breed_transfer('./images/Curly-coated_retriever_03896.jpg'))
print(predict_breed_transfer('./images/Labrador_retriever_06455.jpg'))
print(predict_breed_transfer('./images/Welsh_springer_spaniel_08203.jpg'))
Curly-coated retriever Labrador retriever Irish red and white setter
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!

### Write your algorithm.
### Feel free to use as many code cells as needed.
def run_app(img_path):
## handle cases for a human face, dog, and neither
image = Image.open(img_path)
plt.imshow(image)
plt.show()
if (dog_detector(img_path)):
prediction = predict_breed_transfer(img_path)
print("Dog detected :) Dog breed is : ", prediction)
print("Image path : ", img_path)
elif (face_detector(img_path)):
prediction = predict_breed_transfer(img_path)
print("Human detected. Resembling dog breed is : ", prediction, " :)")
else:
print("Error occured! :(")
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: (Three possible points for improvement)
Yes, model works like a charm.
1-) If there were more dog images in our dataset, our model could be trained better and we could get better results.
2-) Human detector is very simple. If we had CNN based detector, we could get better results to detect human faces.
3-) I could try more augmentation on dataset to observe getting better results.
# Generate test files here
indices = list(range(len(human_files)))
np.random.shuffle(indices)
human_files_test = human_files[indices[:20]]
dog_files_test = np.array(glob("dogImages/test/*/*"))
indices = list(range(len(dog_files_test)))
np.random.shuffle(indices)
dog_files_test = dog_files_test[indices[:20]]
## Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
## suggested code, below
for file in np.hstack((human_files_test, dog_files_test)):
run_app(file)
Human detected. Resembling dog breed is : Yorkshire terrier :)
Human detected. Resembling dog breed is : Poodle :)
Human detected. Resembling dog breed is : Cavalier king charles spaniel :)
Human detected. Resembling dog breed is : American water spaniel :)
Human detected. Resembling dog breed is : Australian shepherd :)
Human detected. Resembling dog breed is : Cavalier king charles spaniel :)
Human detected. Resembling dog breed is : Chinese crested :)
Human detected. Resembling dog breed is : Australian shepherd :)
Human detected. Resembling dog breed is : Neapolitan mastiff :)
Human detected. Resembling dog breed is : Basenji :)
Human detected. Resembling dog breed is : Chinese crested :)
Human detected. Resembling dog breed is : Poodle :)
Human detected. Resembling dog breed is : Glen of imaal terrier :)
Human detected. Resembling dog breed is : Basenji :)
Human detected. Resembling dog breed is : Basenji :)
Human detected. Resembling dog breed is : German shepherd dog :)
Human detected. Resembling dog breed is : English springer spaniel :)
Human detected. Resembling dog breed is : Chinese crested :)
Human detected. Resembling dog breed is : Chinese crested :)
Human detected. Resembling dog breed is : Kerry blue terrier :)
Dog detected :) Dog breed is : Great pyrenees Image path : dogImages/test/079.Great_pyrenees/Great_pyrenees_05415.jpg
Dog detected :) Dog breed is : Mastiff Image path : dogImages/test/103.Mastiff/Mastiff_06873.jpg
Dog detected :) Dog breed is : Parson russell terrier Image path : dogImages/test/116.Parson_russell_terrier/Parson_russell_terrier_07531.jpg
Dog detected :) Dog breed is : French bulldog Image path : dogImages/test/069.French_bulldog/French_bulldog_04813.jpg
Dog detected :) Dog breed is : Airedale terrier Image path : dogImages/test/003.Airedale_terrier/Airedale_terrier_00207.jpg
Dog detected :) Dog breed is : Cavalier king charles spaniel Image path : dogImages/test/046.Cavalier_king_charles_spaniel/Cavalier_king_charles_spaniel_03309.jpg
Dog detected :) Dog breed is : Brittany Image path : dogImages/test/037.Brittany/Brittany_02607.jpg
Human detected. Resembling dog breed is : Australian cattle dog :)
Dog detected :) Dog breed is : German shepherd dog Image path : dogImages/test/071.German_shepherd_dog/German_shepherd_dog_04910.jpg
Dog detected :) Dog breed is : Bearded collie Image path : dogImages/test/089.Irish_wolfhound/Irish_wolfhound_06052.jpg
Dog detected :) Dog breed is : Afghan hound Image path : dogImages/test/002.Afghan_hound/Afghan_hound_00125.jpg
Dog detected :) Dog breed is : German shorthaired pointer Image path : dogImages/test/072.German_shorthaired_pointer/German_shorthaired_pointer_04986.jpg
Dog detected :) Dog breed is : Ibizan hound Image path : dogImages/test/083.Ibizan_hound/Ibizan_hound_05693.jpg
Dog detected :) Dog breed is : Bull terrier Image path : dogImages/test/039.Bull_terrier/Bull_terrier_02775.jpg
Dog detected :) Dog breed is : American water spaniel Image path : dogImages/test/009.American_water_spaniel/American_water_spaniel_00631.jpg
Dog detected :) Dog breed is : Bull terrier Image path : dogImages/test/039.Bull_terrier/Bull_terrier_02803.jpg
Dog detected :) Dog breed is : Affenpinscher Image path : dogImages/test/001.Affenpinscher/Affenpinscher_00078.jpg
Dog detected :) Dog breed is : Entlebucher mountain dog Image path : dogImages/test/065.Entlebucher_mountain_dog/Entlebucher_mountain_dog_04597.jpg
Dog detected :) Dog breed is : Kuvasz Image path : dogImages/test/095.Kuvasz/Kuvasz_06429.jpg
Dog detected :) Dog breed is : Golden retriever Image path : dogImages/test/076.Golden_retriever/Golden_retriever_05221.jpg